﻿using AngelCMS.module.BLL;
using AngelCMS.module.Models;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AngelCMS.Controllers
{
    public class FileController : Controller
    {
        // GET: Admin

        MatchBLL matchBLL = new MatchBLL();
        public ActionResult Index()
        { 
            return View();
        }
        public string ImportUser() {
            var oFile = Request.Files["file_data"];
            var f = Request.Files;
            //var lstOrderImport = new List<DTO_TO_ORDER_IMPORT>();
            var ID = Request["ID"];
            var AreaID= Request["AreaID"];
            //var iMax_Import_Index = lstExistOrder.Max(x => x.IMPORT_INDEX);
            //iMax_Import_Index = iMax_Import_Index == null ? 0 : iMax_Import_Index.Value;
            ReturnMsg msg = new ReturnMsg();

            IWorkbook workbook = null;
            if (oFile.FileName.EndsWith(".xls"))
            {
                workbook = new HSSFWorkbook(oFile.InputStream);
            }
            else if (oFile.FileName.EndsWith(".xlsx"))
            {
                workbook = new XSSFWorkbook(oFile.InputStream);
            }
            else {
                msg.msg = "请上传.xls和.xlsx格式的文件";
                msg.status = 0;
                return JsonConvert.SerializeObject(msg);
            }
            if (workbook == null)
            {
                msg.msg = "服务器有误，请联系管理员";
                msg.status = 0;
                return JsonConvert.SerializeObject(msg);
            }

            DataTable dt = NPOIHelper.ExcelToDataTable(workbook, null, 0, 0);
            var isUserName = dt.Columns.Contains("选手姓名");
            var isGrades = dt.Columns.Contains("成绩");
            var isPhoneNumber = dt.Columns.Contains("手机号");
            var isTicketCode = dt.Columns.Contains("票码");
           

            if (!(isUserName && isGrades && isPhoneNumber && isTicketCode ))
            {
                msg.msg = "模板有误";
                msg.status = 0;
                return JsonConvert.SerializeObject(msg);
            }
            //...............处理excel的逻辑
            if (dt != null && dt.Rows.Count > 0) {
                UserInfoBLL userInfoBLL = new UserInfoBLL();
                for (int i = 0; i < dt.Rows.Count; i++) {
                    UserInfo m = new UserInfo();
                    DataRow dr = dt.Rows[i];
                    m.UserName = dr["选手姓名"].ToString();
                    m.Grades = dr["成绩"].ToString();
                    m.PhoneNumber = dr["手机号"].ToString();
                    m.TicketCode = dr["票码"].ToString();
                    m.IsFinal = dr[5].ToString()=="是"?1:0;
                    m.MatchID = Convert.ToInt32(ID);
                    m.AreaID = Convert.ToInt32(AreaID);
                    userInfoBLL.AddUsersInfo(m);
                }
                msg.msg = "上传成功,成功导入" + dt.Rows.Count+"条";
                msg.status = 1;
                return JsonConvert.SerializeObject(msg);
            }
            else {
                msg.msg = "上传成功，但是数量为0";
                msg.status = 0;
                return JsonConvert.SerializeObject(msg);
            }

            //orderManager.Add(lstOrder);
            // lstOrderImport = lstOrderImport.OrderBy(x => x.IMPORT_STATU).ToList();
           
        }

        public object ImportQrcode()
        {
          //  var oFile = Request.Files["file_data"];
            if (Request.Files.Count > 0)
            {
                var f = Request.Files;
                var oFile = Request.Files[0];
                //var lstOrderImport = new List<DTO_TO_ORDER_IMPORT>();
                var ID = Request["ID"];
                string qrcode = DateTime.Now.ToString("yyyyMMddHHmmss");
                string extend = oFile.FileName.Substring(oFile.FileName.LastIndexOf("."));
                //var iMax_Import_Index = lstExistOrder.Max(x => x.IMPORT_INDEX);
                //iMax_Import_Index = iMax_Import_Index == null ? 0 : iMax_Import_Index.Value;

                string filename = qrcode + extend;
                IWorkbook workbook = null;
                if (oFile.FileName.EndsWith(".jpg") || oFile.FileName.EndsWith("png"))
                {
                    string updir = Server.MapPath("/QrCode/");
                    if (!Directory.Exists(updir))
                    { Directory.CreateDirectory(updir); }
                    string oldFullName = Path.Combine(updir, filename);
                    oFile.SaveAs(oldFullName);
                    return new { };
                }
                if (workbook == null)
                {
                    return new { };
                }

            }
                //orderManager.Add(lstOrder);
                // lstOrderImport = lstOrderImport.OrderBy(x => x.IMPORT_STATU).ToList();
                return new { };
            }
        
    }
}